import axios from 'axios';
// import { message as createMessage, message } from "ant-design-vue";
import store from '/@/store';
import { API_URL } from '/@/utils/constants';

const service = axios.create({
  baseURL: API_URL,
  timeout: 5000,
});

// http请求拦截器
service.interceptors.request.use(
  (config) => {
    const { accessToken } = store.getters;
    if (accessToken) config.headers.Authorization = `Bearer  ${accessToken}`;
    if (config.method == 'post') {
      config.params = {};
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// http响应拦截器
service.interceptors.response.use(
  (response) => {
    const { statusCode, result, message: Message } = response.data;
    if (statusCode === 0) {
      // createMessage.success(Message);
      return result;
    }
  },
  (err) => {
    const {
      data: { statusCode, message: Message },
    } = err.response;
    if (statusCode === 401 || statusCode === 403 || statusCode === 501 || statusCode === 502) {
      store.dispatch('setLoginStatus', 0);
      store.dispatch('setAccessToken', '');

      statusCode === 501 && store.dispatch('setScopeNumber', 1);
      window.location.reload();
    } else {
      // TODO错误提示
      // createMessage.error({ message: Message });
    }
    return Promise.reject(err);
  }
);

export default service;
